using AdminApiTemplate.Common.Enums;
using AdminApiTemplate.Common.Exceptions;
using Dapper;
using System.Data;

namespace AdminApiTemplate.Services.WorkWx
{
    public class WorkWxService
    {
        private readonly IDbConnection _dbConnection;

        public WorkWxService(
            IDbConnection dbConnection)
        {
            _dbConnection = dbConnection;
        }

        public async Task<string> GetAccessTokenAsync(string corpId)
        {
            var sql = "select AccessToken,ExpireTime from AccessTokenLog where CorpId=@corpId order by Id desc";
            var items = await _dbConnection.QueryFirstOrDefaultAsync<WorkWxAccessTokenDto>(sql, new { corpId });
            var one = items;
            if (one != null && one.ExpireTime.GetValueOrDefault() > DateTime.Now && !string.IsNullOrEmpty(one.AccessToken))
            {
                return one.AccessToken;
            }

            return null;
        }

        public async Task<string> UpdateAccessTokenAsync(string corpId, string accessToken, DateTime? expireTime)
        {
            var sql = "insert into AccessTokenLog(CreateTime,CorpId,AccessToken,ExpireTime) values(NOW(),@CorpId,@AccessToken,@ExpireTime)";
            await _dbConnection.ExecuteAsync(sql, new { corpId, accessToken, expireTime });
            return "已更新AccessToken";
        }

        /// <summary>
        /// 发送文本消息给企业微信用户
        /// </summary>
        /// <param name="content"></param>
        /// <param name="users"></param>
        /// <returns></returns>
        public async Task<string> SendTextToUserAsync(string content, string title, string url, params string[] users)
        {
            if (string.IsNullOrEmpty(content))
            {
                throw new WithCodeException((int)ErrorCodeEnum.CodeError, "请填写发送的内容", "content必填");
            }

            if (users == null || users.Length == 0)
            {
                throw new WithCodeException((int)ErrorCodeEnum.CodeError, "请选择要发送给的用户", "users必填");
            }

            var sql = $"insert into queuesendworkwxmsg(CreateTime,SendingStatus,Content,ToUser,Title,Url) values(NOW(),{(int)SendingStatusEnum.ReadyToSend},@content,@ToUser,@title,@url)";
            await _dbConnection.ExecuteAsync(sql, new { content, ToUser = string.Join(",", users), title, url });
            return "已添加到发送队列，将在后台发送";
        }
    }
}
